package cn.cainiao.dao;


import java.sql.*;

public class BaseDao {
    public static Connection getConn() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cainiaoyizhan", "root", "root");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(conn != null){
            System.out.println("mysql连接正常");
        }else {
            System.out.println("mysql连接异常");
        }
        return conn;
    }

    public static int exectuIUD(String sql, Object[] params) {
        int count = 0;
        Connection conn = BaseDao.getConn();
        //准备SQL
        PreparedStatement ps = null;
        // insert into user(''''''','') value(?, ?, ?)
        try {
            //准备SQL
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            count = ps.executeUpdate();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(null, ps, conn);
        }
        return count;
    }


    public static void closeAll(ResultSet rs, Statement stat, Connection conn) {
        try {
            if (rs != null)
                rs.close();
            if (stat != null)
                stat.close();
            if (conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}